package com.wx.tourism.controller;

import com.alibaba.fastjson.JSON;
import com.wx.tourism.model.Car;
import com.wx.tourism.service.CarService;
import com.wx.utils.AjaxMessage;
import com.wx.utils.AjaxMsg;
import com.wx.utils.Page;
import com.wx.utils.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by myd on 16/5/7.
 */
@Controller("carController")
@RequestMapping("/car")
public class CarController {

    @Resource(name = "carServiceImpl")
    private CarService<Car> carService;

    /**
     * 分页获取数据action
     * @param pageable
     * @param car
     * @return
     */
    @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Page<Car> list(Pageable pageable, Car car)
    {
        return carService.findPage(pageable,car);
    }

    /**
     * 保存信息
     * @param datas
     */
    @RequestMapping(value = "/save", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxMessage save(String datas)
    {
        int result = 0;
        String msg = "";
        try {
            List<Car> cars = JSON.parseArray("["+datas+"]",Car.class);
            for (Car car : cars)
            {
                result = this.carService.save(car);
            }
            if (result != 0)
            {
                msg = "删除成功!";
            }
            else {
                msg = "删除失败!";
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return new AjaxMessage(0 != result ? true : false, msg);
    }

    /**
     * 根据主键批量删除
     * @param ids 主键集合,使用逗号分隔
     */
    @RequestMapping(value = "/delete",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public AjaxMessage delete(String ids)
    {
        System.out.println("删除"+ids);
        int result = 0;
        String msg = "";
        try{
            String[] tmps = ids.split(",");
            if(null != tmps && tmps.length > 0) {
                List<String> idList = new ArrayList<String>();
                for(String s: tmps) {
                    idList.add(s);
                }

                result = this.carService.delete(idList);
            }

            if (result != 0)
            {
                msg = "删除成功!";
            }
            else {
                msg = "删除失败!";
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return new AjaxMessage(0 != result ? true : false, msg);
    }
}
